package api

import (
	"admin100/app/api/statistics"
	"admin100/app/model"
	"admin100/app/model/gamemodel"
	"admin100/app/service"
	"admin100/app/service/centerservice"
	"admin100/app/service/chargeservice"
	"admin100/app/service/commonservice"
	"admin100/app/service/gameservice"
	"admin100/library/define"
	"admin100/library/define/defErr"
	"admin100/library/response"
	"admin100/library/utils"
	util_math "admin100/library/utils/math"
	"strings"

	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/text/gstr"
)

var StatisticsMgr = statisticsApi{}

type statisticsApi struct{}

// @summary 服务器概况
// @tags 数据和统计
// @produce json
// @param   platformId formData  string true "平台id"
// @param   serverId formData  string true "服务号id"
// @param   channelList formData  string true "渠道列表,如： all, local_test"
// @router  /statistics/get-server-generalize [POST]
// @success 200 {object} response.JsonResponse "执行结果"
func (a *statisticsApi) GetServerGeneralize(r *ghttp.Request) {
	var req = model.ServerGeneralizeParam{}
	if err := r.ParseForm(&req); err != nil {
		defErr.Panic(define.Fail, err.Error())
	}

	if gstr.Trim(req.PlatformId) == "" || gstr.Trim(req.ServerId) == "" {
		defErr.Panic(define.RecordNodFound)
	}

	_, gameServer := centerservice.CGameServer.GetGameServerList(req.PlatformId, []string{req.ServerId}, true)
	node := gameServer.Node
	//gameDb := commondao.DB.NewCustomGdb(node)

	serverNode := centerservice.CGameNode.GetServerNode(node)
	var channelSlice []string
	if gstr.Trim(req.ChannelList) != "" {
		channelSlice = strings.Split(req.ChannelList, ",")
		for k, v := range channelSlice {
			channelSlice[k] = gstr.Trim(v)
		}
	}
	chargeTimesList := chargeservice.ChargeInfoRecord.GetServerChargeCountList(req.PlatformId, req.ServerId, channelSlice)
	var (
		chargeCount2 = 0
		chargeCount3 = 0
		chargeCount5 = 0
	)
	for _, v := range chargeTimesList {
		if v.Int() >= 2 {
			chargeCount2++
		}
		if v.Int() >= 3 {
			chargeCount3++
		}
		if v.Int() >= 5 {
			chargeCount5++
		}
	}

	todayZeroTime := utils.GetTodayZeroTimestamp()
	res := &model.ServerGeneralizeResponse{
		PlatformId:              gameServer.PlatformId,
		ServerId:                centerservice.CGameServer.GetGameServerIdListStringByNode(node),
		OpenTime:                serverNode.OpenTime,
		Version:                 gameservice.ServerData.GetNodeVersion(node),
		MergeTime:               gameservice.ServerData.GetMergeTime(node),
		Status:                  serverNode.State,
		TotalRegister:           gameservice.Account.GetTotalRegisterRoleCountByChannelList(node, gameServer.Sid, channelSlice),
		TotalCreateRole:         gameservice.Account.GetTotalCreateRoleCountByChannelList(node, gameServer.Sid, channelSlice),
		OnlineCount:             commonservice.GamePlayer.GetNowOnlineCount2(node, gameServer.Sid, channelSlice),
		MaxLevel:                gameservice.PlayerData.GetMaxPlayerLevel(node, gameServer.Sid, channelSlice),
		TodayCreateRole:         gameservice.Account.GetCreateRoleCountByChannelList(node, gameServer.Sid, channelSlice, todayZeroTime, todayZeroTime+86400),
		TodayRegister:           gameservice.Account.GetRegisterRoleCountByChannelList(node, gameServer.Sid, channelSlice, todayZeroTime, todayZeroTime+86400),
		MaxOnlineCount:          service.TenMinuteStatistics.GetThatDayMaxOnlineCount(gameServer.PlatformId, gameServer.Sid, channelSlice, todayZeroTime, todayZeroTime+86400),
		YesterdayMaxOnlineCount: service.TenMinuteStatistics.GetThatDayMaxOnlineCount(gameServer.PlatformId, gameServer.Sid, channelSlice, todayZeroTime-86400, todayZeroTime),
		TotalChargeIngot:        chargeservice.ChargeInfoRecord.GetServerTotalChargeIngot(gameServer.PlatformId, gameServer.Sid, channelSlice),
		TotalChargeMoney:        chargeservice.ChargeInfoRecord.GetServerTotalChargeMoneyByChannelList(gameServer.PlatformId, gameServer.Sid, channelSlice),
		TotalChargePlayerCount:  chargeservice.ChargeInfoRecord.GetServerChargePlayerCount(gameServer.PlatformId, gameServer.Sid, channelSlice),
		SecondChargePlayerCount: chargeservice.ChargeInfoRecord.GetServerSecondChargePlayerCount(gameServer.PlatformId, gameServer.Sid, channelSlice),
		TotalIngot:              gameservice.PlayerProp.GetTotalProp(node, 1, 2, channelSlice),
		TotalCoin:               gameservice.PlayerProp.GetTotalProp(node, 1, 1, channelSlice),
	}

	//
	res.ARPU = util_math.CaclRate(res.TotalChargeMoney, res.TotalChargePlayerCount)
	res.ChargeRate = util_math.CaclRate(res.TotalChargePlayerCount, res.TotalCreateRole)
	res.SecondChargeRate = util_math.CaclRate(res.SecondChargePlayerCount, res.TotalChargePlayerCount)
	res.ChargeCount2Rate = util_math.CaclRate(chargeCount2, res.TotalChargePlayerCount)
	res.ChargeCount3Rate = util_math.CaclRate(chargeCount3, res.TotalChargePlayerCount)
	res.ChargeCount5Rate = util_math.CaclRate(chargeCount5, res.TotalChargePlayerCount)

	response.JsonSuc(r, res)
}

// @summary 每日汇总
// @tags 数据和统计
// @produce json
// @param   platformId formData  string true "平台id"
// @param   serverId formData  string true "服务号id"
// @param   channelList formData  string flase "渠道列表,如： all, local_test"
// @param   startTime formData  string true "开始时间"
// @param   endTime formData  string true "结束时间"
// @router  /statistics/daily-statistics [POST]
// @success 200 {object} response.JsonResponse "执行结果"
func (a *statisticsApi) DailyStatistics(r *ghttp.Request) {
	var req = model.DailyStatisticsReq{}
	if err := r.ParseForm(&req); err != nil {
		defErr.Panic(define.Fail, err.Error())
	}

	if req.EndTime < req.StartTime {
		defErr.Panic(define.TimeErrStartEnd)
	}

	res := service.Statistics.FetchDailyStatistics(&req)
	response.JsonSuc(r, map[string]interface{}{
		"rows": res,
	})
}

// @summary 消费产出分析
// @tags 数据和统计
// @produce json
// @param   platformId formData  string true "平台id"
// @param   serverId formData  string true "服务号id"
// @param   channelList formData  string true "渠道列表,如： all, local_test"
// @param   playerName formData  string false "角色名"
// @param   propType formData  string false "道具类型"
// @param   propId formData  string false "道具id"
// @param   type formData  string false "类型 : 获得 or 消耗"
// @param   startTime formData  string false "开始时间"
// @param   endTime formData  string false "结束时间"
// @param   cur formData  int true "当前页数"
// @param   pNum formData  int true "每页记录数量"
// @router  /statistics/consume-analysis [POST]
// @success 200 {object} response.JsonResponse "执行结果"
func (a *statisticsApi) ConsumeAnalysis(r *ghttp.Request) {
	var req = gamemodel.ConsumeAnalysisReq{}
	if err := r.ParseForm(&req); err != nil {
		defErr.Panic(define.Fail, err.Error())
	}

	if req.PlayerName != "" {
		serverId, _ := commonservice.GamePlayer.SplitPlayerName(req.PlayerName)
		sNode := centerservice.CGameServer.FetchNodeStrByPtIdAndSid(req.PlatformId, serverId)
		player := commonservice.GamePlayer.GetPlayerByPlatformIdAndNickname(sNode, req.PlayerName)
		if player == nil {
			defErr.Panic(define.PlayerNotExist)
		}
		req.PlayerId = int(player.Id)
	}

	response.JsonSuc(r, g.Map{"rows": gameservice.Consume.GetPropConsumeStatistics(&req)})
}

// @summary 充值订单查询
// @tags 数据和统计
// @produce json
// @param   platformId formData  string true "平台id"
// @param   serverId formData  string true "服务号id"
// @param   platformOrderId formData  string false "第三方订单号"
// @param   channelList formData  string true "渠道列表,如： all, local_test"
// @param   playerId formData  string false "玩家id"
// @param   playerName formData  string false "角色名"
// @param   orderId formData  string false "订单号"
// @param   accId formData  string false "帐号"
// @param   startTime formData  string false "开始时间"
// @param   endTime formData  string false "结束时间"
// @param   cur formData  int true "当前页数"
// @param   pNum formData  int true "每页记录数量"
// @router  /statistics/charge-list [POST]
// @success 200 {object} response.JsonResponse "执行结果"
func (a *statisticsApi) ChargeList(r *ghttp.Request) {

	var req = gamemodel.ChargeInfoRecordQueryReq{}
	if err := r.ParseForm(&req); err != nil {
		defErr.Panic(define.Fail, err.Error())
	}

	if req.PlayerName != "" {
		serverId, _ := commonservice.GamePlayer.SplitPlayerName(req.PlayerName)
		sNode := centerservice.CGameServer.FetchNodeStrByPtIdAndSid(req.PlatformId, serverId)
		player := commonservice.GamePlayer.GetPlayerByPlatformIdAndNickname(sNode, req.PlayerName)
		if player == nil {
			defErr.Panic(define.PlayerNotExist)
		}
		req.PlayerId = int(player.Id)
	}
	resp := chargeservice.ChargeInfoRecord.GetChargeInfoRecordList(&req)

	result := make(map[string]interface{})
	result["total"] = resp.Total
	result["playerCount"] = resp.SumPlayerCount
	result["moneyCount"] = resp.SumMoneyCount
	result["chargeTotalMoney"] = resp.ChargeTotalMoney
	result["exchangeRate"] = resp.ExchangeRate
	result["data"] = resp.Data

	response.JsonSuc(r, result)
}

// @summary 留存数据_总体留存
// @tags 数据和统计
// @produce json
// @param   platformId formData  string true "平台id"
// @param   serverId formData  string false "服务号id"
// @param   channelList formData  string true "渠道列表,如： all, local_test"
// @param   startTime formData  string true "开始时间"
// @param   endTime formData  string true "结束时间"
// @router  /statistics/total-remain [POST]
// @success 200 {object} response.JsonResponse "执行结果"
func (a *statisticsApi) TotalRemain(r *ghttp.Request) {
	statistics.RemainMgr.Total(r)
}

// @summary 留存数据_付费次留
// @tags 数据和统计
// @produce json
// @param   platformId formData  string true "平台id"
// @param   serverId formData  string false "服务号id"
// @param   channelList formData  string true "渠道列表,如： all, local_test"
// @param   startTime formData  string true "开始时间"
// @param   endTime formData  string true "结束时间"
// @router  /statistics/charge-remain [POST]
// @success 200 {object} response.JsonResponse "执行结果"
func (a *statisticsApi) ChargeRemain(r *ghttp.Request) {
	statistics.RemainMgr.Charge(r)
}

// @summary 留存数据_活跃留存
// @tags 数据和统计
// @produce json
// @param   cur query int true "当前页数"
// @param   PNum query int true "每页数据数量"
// @param   platformId formData  string true "平台id"
// @param   serverId formData  string false "服务号id"
// @param   channelList formData  string true "渠道列表,如： all, local_test"
// @param   startTime formData  string true "开始时间"
// @param   endTime formData  string true "结束时间"
// @router  /statistics/active-remain [POST]
// @success 200 {object} response.JsonResponse "执行结果"
func (a *statisticsApi) ActiveRemain(r *ghttp.Request) {
	statistics.RemainMgr.Active(r)
}

// @summary 留存数据_等级流失(分布)
// @tags 数据和统计
// @produce json
// @param   platformId formData  string true "平台id"
// @param   serverId formData  string false "服务号id"
// @param   channelList formData  string true "渠道列表 "
// @param   isChargePlayer formData  int true "是否付费玩家"
// @param   startTime formData  string false "开始时间"
// @param   endTime formData  string false "结束时间"
// @router  /statistics/level-remain [POST]
// @success 200 {object} response.JsonResponse "执行结果"
func (a *statisticsApi) LevelRemain(r *ghttp.Request) {
	statistics.RemainMgr.Level(r)
}

// @summary 留存数据_任务流失(分布)
// @tags 数据和统计
// @produce json
// @param   platformId formData  string true "平台id"
// @param   serverId formData  string false "服务号id"
// @param   channelList formData  string true "渠道列表 "
// @param   isChargePlayer formData  int true "是否付费玩家"
// @router  /statistics/task-remain [POST]
// @success 200 {object} response.JsonResponse "执行结果"
func (a *statisticsApi) TaskRemain(r *ghttp.Request) {
	statistics.RemainMgr.Task(r)
}

// @summary 留存数据_时长流失(分布)
// @tags 数据和统计
// @produce json
// @param   platformId formData  string true "平台id"
// @param   serverId formData  string false "服务号id"
// @param   channelList formData  string true "渠道列表 "
// @param   isChargePlayer formData  int true "是否付费玩家"
// @param   startTime formData  string false "开始时间"
// @param   endTime formData  string false "结束时间"
// @router  /statistics/time-remain [POST]
// @success 200 {object} response.JsonResponse "执行结果"
func (a *statisticsApi) TimeRemain(r *ghttp.Request) {
	statistics.RemainMgr.Time(r)
}

// @summary 10分钟在线注册
// @tags 数据和统计
// @produce json
// @param   platformId formData  string true "平台id"
// @param   serverId formData  string false "服务号id"
// @param   channelList formData  string true "渠道列表 "
// @router  /statistics/real-time-online [POST]
// @success 200 {object} response.JsonResponse "执行结果"
func (a *statisticsApi) RealTimeOnline(r *ghttp.Request) {
	statistics.RemainMgr.RealTimeOnline(r)
}

// @summary 注册充值
// @tags 数据和统计
// @produce json
// @param   platformId formData  string true "平台id"
// @param   serverId formData  string true "服务号id"
// @param   promote formData  string false "邀请码"
// @param   channelList formData  string true "渠道列表,如： all, local_test"
// @param   startTime formData  string true "开始时间"
// @param   endTime formData  string true "结束时间"
// @param   cur query int true "当前页数"
// @param   PNum query int true "每页数据数量"
// @router  /statistics/req-recharge [POST]
// @success 200 {object} response.JsonResponse "执行结果"
func (a *statisticsApi) RegRecharge(r *ghttp.Request) {
	statistics.ChargeMgr.RegRecharge(r)
}

// @summary 充值分析_LTV
// @tags 数据和统计
// @produce json
// @param   platformId formData  string true "平台id"
// @param   serverId formData  string true "服务号id"
// @param   promote formData  string false "邀请码"
// @param   channelList formData  string true "渠道列表,如： all, local_test"
// @param   startTime formData  string true "开始时间"
// @param   endTime formData  string true "结束时间"
// @param   cur query int true "当前页数"
// @param   PNum query int true "每页数据数量"
// @router  /statistics/charge-daily-ltv [POST]
// @success 200 {object} response.JsonResponse "执行结果"
func (a *statisticsApi) ChargeDailyLtv(r *ghttp.Request) {
	statistics.ChargeMgr.GetDailyLtv(r)
}

// @summary 充值分析_充值对比
// @tags 数据和统计
// @produce json
// @param   platformId formData  string true "平台id"
// @param   serverId formData  string true "服务号id"
// @param   channelList formData  string true "渠道列表,如： all, local_test"
// @router  /statistics/charge-statistics [POST]
// @success 200 {object} response.JsonResponse "执行结果"
func (a *statisticsApi) ChargeStatistics(r *ghttp.Request) {
	statistics.ChargeMgr.Statistics(r)
}

// @summary 充值分析_流水曲线
// @tags 数据和统计
// @produce json
// @param   platformId formData  string true "平台id"
// @param   serverId formData  string true "服务号id"
// @param   channelList formData  string true "渠道列表,如： all, local_test"
// @param   startTime formData  string true "开始时间"
// @param   endTime formData  string true "结束时间"
// @router  /statistics/income-statistics [POST]
// @success 200 {object} response.JsonResponse "执行结果"
func (a *statisticsApi) IncomeStatistics(r *ghttp.Request) {
	statistics.ChargeMgr.IncomeStatistics(r)
}

// @summary 充值分析_充值金额分布
// @tags 数据和统计
// @produce json
// @param   platformId formData  string true "平台id"
// @param   serverId formData  string true "服务号id"
// @param   channelList formData  string true "渠道列表,如： all, local_test"
// @param   promote formData  string false "邀请码"
// @router  /statistics/charge-money-distribution [POST]
// @success 200 {object} response.JsonResponse "执行结果"
func (a *statisticsApi) ChargeMoneyDistribution(r *ghttp.Request) {
	statistics.ChargeMgr.ChargeMoneyDistribution(r)
}

// @summary 充值分析_充值活动分布
// @tags 数据和统计
// @produce json
// @param   platformId formData  string true "平台id"
// @param   serverId formData  string true "服务号id"
// @param   channelList formData  string true "渠道列表,如： all, local_test"
// @param   promote formData  string false "邀请码"
// @param   startTime formData  string true "开始时间"
// @param   endTime formData  string true "结束时间"
// @router  /statistics/charge-activity-distribution [POST]
// @success 200 {object} response.JsonResponse "执行结果"
func (a *statisticsApi) ChargeActivityDistribution(r *ghttp.Request) {
	statistics.ChargeMgr.ChargeActivityDistribution(r)
}

// @summary 充值分析_充值等级分布
// @tags 数据和统计
// @produce json
// @param   platformId formData  string true "平台id"
// @param   serverId formData  string true "服务号id"
// @param   channelList formData  string true "渠道列表,如： all, local_test"
// @param   promote formData  string false "邀请码"
// @router  /statistics/charge-level-distribution [POST]
// @success 200 {object} response.JsonResponse "执行结果"
func (a *statisticsApi) ChargeLevelDistribution(r *ghttp.Request) {
	statistics.ChargeMgr.ChargeLevelDistribution(r)
}

// @summary 充值分析_充值任务分布
// @tags 数据和统计
// @produce json
// @param   platformId formData  string true "平台id"
// @param   serverId formData  string true "服务号id"
// @param   channelList formData  string true "渠道列表,如： all, local_test"
// @param   promote formData  string false "邀请码"
// @router  /statistics/charge-task-distribution [POST]
// @success 200 {object} response.JsonResponse "执行结果"
func (a *statisticsApi) ChargeTaskDistribution(r *ghttp.Request) {
	statistics.ChargeMgr.ChargeTaskDistribution(r)
}

// @summary 充值分析_充值排行
// @tags 数据和统计
// @produce json
// @param   platformId formData  string true "平台id"
// @param   serverId formData  string true "服务号id"
// @param   channelList formData  string true "渠道列表,如： all, local_test"
// @param   startTime formData  string true "开始时间"
// @param   endTime formData  string true "结束时间"
// @param   cur query int true "当前页数"
// @param   PNum query int true "每页数据数量"
// @router  /statistics/charge-rank [POST]
// @success 200 {object} response.JsonResponse "执行结果"
func (a *statisticsApi) ChargeRank(r *ghttp.Request) {
	statistics.ChargeMgr.ChargeRankList(r)
}
